package com.ruoyi.handler;

import java.nio.ByteBuffer;

import org.apache.commons.codec.binary.Hex;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

import com.ruoyi.session.DeviceManager;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

@Sharable
@Slf4j
@Service
public class Tcp9001Handler extends SimpleChannelInboundHandler<ByteBuf> {


    AttributeKey<String> productKey = AttributeKey.valueOf("productKey");

    AttributeKey<String> channelKey = AttributeKey.valueOf("channelKey");

    AttributeKey<String> deviceKey = AttributeKey.valueOf("deviceKey");

    @Resource
    private DeviceManager deviceManager;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

        byte[] data = new byte[msg.readableBytes()];
		msg.readBytes(data);
        log.info("收到客户端{}消息：{}" ,ctx.channel().remoteAddress(), Hex.encodeHexString(data));

        // 实际应该是设备上线注册后，解析出设备标识，再进行添加
        if(true){
            // 解析出设备标识，设备标识长度根据设备自定义
            byte[] deviceKeyByteArray = new byte[8];
            System.arraycopy(data, 0, deviceKeyByteArray, 0, deviceKeyByteArray.length);
            // 将设备标识与该tcp连接绑定
            ctx.channel().attr(deviceKey).set(new String(deviceKeyByteArray));
            // 将连接信息保存到在线队列
            deviceManager.addDevice(ctx.channel().attr(deviceKey).get(), ctx);
            return;
        }
 

        // 回复消息demo
        ctx.writeAndFlush(Unpooled.copiedBuffer(data));
        log.info("回复给设备消息：{}", Hex.encodeHexString(data));

        // 这里是解析数据内容demo写法
        //byte[] wendu_byte = new byte[4];	
        //byte[] shidu_byte = new byte[4];	
        //System.arraycopy(data, 0, wendu_byte, 0, wendu_byte.length);	
        //System.arraycopy(data, 4, shidu_byte, 0, shidu_byte.length);
        // 温度  Ints.fromByteArray(byteArray);
        //float wendu = ByteBuffer.wrap(wendu_byte).getFloat();
        // 湿度 Floats.fromByteArray(byteArray);
        //float shidu =ByteBuffer.wrap(shidu_byte).getFloat();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        // 设备掉线事件，心跳检测超时，或者网络断开都会触发这个事件
        if(ctx.channel().attr(deviceKey).get()!=null){
            deviceManager.removeDevice(ctx.channel().attr(deviceKey).get());
        }
        log.info("触发事件:{}", evt);
    }
    

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        if(ctx.channel().attr(deviceKey).get()!=null){
            deviceManager.removeDevice(ctx.channel().attr(deviceKey).get());
        }
        log.info("客户端断开连接:{}", ctx.channel().remoteAddress());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        log.info("客户端连接成功:{}", ctx.channel().remoteAddress());
    }


}
